import React, { useState, useEffect } from "react";
import {
  balanceOf,
  getMetadata,
  safeTransferFrom,
  tokenOfOwnerByIndex,
} from "../contracts/helper/erc721.js";
import style from "../css/MyPet.css";

import { SEPOLIA_NET } from "../contracts/const/contractAddress.js";
function MyPet({ address }) {
  const [pets, setPets] = useState([]);
  const [petsInfo, setPetsInfo] = useState([]);

  useEffect(() => {
    const fetchNFTs = async () => {
      const length = await balanceOf(address);
      console.log("length", length);
      for (let i = 0; i < length; i++) {
        const tokenId = await tokenOfOwnerByIndex(address, i);
        console.log("i:", i, "tokenId" + tokenId);
        const metadata = await getMetadata(tokenId);

        // console.log(metadata);
        setPets((prev) => [...prev, metadata]);
        // setPets((prev) => [...new Set(prev)]);
      }
    };
    fetchNFTs();
    console.log("pet");
    console.log(pets);
  }, []);
  const handleRround = async (tokenId) => {
    try {
      // const result = safeTransferFrom(address, SEPOLIA_NET.nftMark, tokenId);
      // console.log(result);
      console.log("handleMint", tokenId);
      console.log(pets);
    } catch (e) {
      console.error(e);
    }
  };

  // Todo my pet
  return (
    <div style={style}>
      <div className="container">
        <div className="row">
          <div>
            <h1
              className="text-center"
              style={{
                textAlign: "center",
                fontSize: "40px",
                fontFamily: "Courier New, Courier, monospace",
                fontWeight: "bold",
                color: "#F5F5DC",
              }}
            >
              My Pet
            </h1>
            <hr />
            <br />
          </div>
        </div>
        <div className="div-petsList">
          <div id="petsRow" style={{ display: "flex", flexWrap: "wrap" }}>
            {pets.map((pet) => (
              <PetCard
                pet={pet}
                handleRround={handleRround}
                key={pet.tokenId}
              />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

const PetCard = ({ pet, handleRround }) => (
  <div className="my-petInfo">
    <div className="panel-heading">
      <h3 className="panel-title">{pet.title}</h3>
    </div>
    <div className="panel-body">
      <div className="cropped-image">
        <img src={pet.images} className="pet-image" />
      </div>
      <button onClick={() => handleRround(pet.tokenId)}>Grounding</button>
    </div>
    {/* </div> */}
  </div>
);

export default MyPet;
